#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/11 11:21
# @Author  : 王凯
# @File    : pdd_crawler.py
# @Project : scrapy_spider
import json
import time

import parsel
import requests
from loguru import logger

from apps.pdd.pdd.utils.js import gen_anti_content, MSG_MAP


class PddCrawler:
    session = requests.Session()

    def __init__(self, cookie=None):
        if cookie is None:
            cookie = {}
        self.base_url = "https://mobile.pinduoduo.com"
        self.session.headers = {
            "Host": "mobile.pinduoduo.com",
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
            "Cache-Control": "no-cache",
        }
        self.session.cookies.update(cookie)
        cookies = self.session.cookies.get_dict()
        self.pdd_user_id = cookies["pdd_user_id"]

    @staticmethod
    def _resolve_raw_data(html):
        response = parsel.Selector(html)
        raw_data = response.re_first(r"window\.rawData\s*=\s*(\{.*\});")
        if not raw_data:
            logger.error("未获取到数据")
            return False
        raw_data = json.loads(raw_data)
        return raw_data

    def get_mall_info(self, mall_id="409099714"):
        url = f"{self.base_url}/mall_page.html?mall_id={mall_id}"
        logger.debug(f"获取店铺url：{url}")
        resp = self.session.get(url).text
        raw_data = self._resolve_raw_data(resp)
        if raw_data is False:
            logger.error(f"店铺【{mall_id}】没有信息 可能账号被封禁")
            return
        mall_basic_info = raw_data["store"]["mallBasicInfo"]
        mall_name = mall_basic_info.get("mallName")
        if not mall_name:
            logger.error(f"店铺【{mall_id}】没有信息 可能账号被封禁")
            return
        logger.info(f"店铺详情：【{mall_id}】【{mall_name}】")
        logger.info(f"获取到店铺信息为：{mall_basic_info}")
        logger.info(f"获取到店铺原始信息为：{raw_data['store']}")

    def get_mall_goods_info(self, mall_id, page_no=1):
        url = f"{self.base_url}/proxy/api/api/turing/mall/query_cat_goods"
        anti_content_dict = gen_anti_content(
            {
                "serverTime": int(time.time() * 1000),
            },
            None,
            {
                "touchEventData": True,
                "clickEventData": True,
                "focusblurEventData": True,
                "changeEventData": True,
                "locationInfo": True,
                "referrer": True,
                "browserSize": True,
                "browserInfo": True,
                "token": True,
                "fingerprint": True,
            },
        )
        anti_content = anti_content_dict["anti_content"]
        params = {
            "pdduid": self.pdd_user_id,
            "anticontent": anti_content,
            "anti_content": anti_content,
            "category_id": "0",
            "type": "0",
            "mall_id": mall_id,
            "page_size": "20",
            "sort_type": "_sales",
            "refer_page_param": "undefined",
            "refer_page_sn": "10014",
            "msn": "jmd2kuhypnw6lwh3qd7gqa65yy_axbuy",
            "flip": "",
            "list_id": "aqjny1juu4cqjxa7",
            "page_from": "39",
            "query": "",
            "goods_id": "495946300192",
            "new_store_goods": "",
            "show_priority_type": "1",
            "show_condition": "null",
            "data_type_list": "1",
            "pair_goods_id_list": "",
            "filter_condition": "",
            "query_shipping_option": "1",
            "card_num_after_last_card": "[]",
            "card_num_total": "",
            "page_no": f"{page_no}",
        }
        headers = {
            **self.session.headers,
            "Referer": f"{self.base_url}/mall_page.html?mall_id={mall_id}",
            "accept": "application/json, text/plain, */*",
        }
        resp = self.session.get(url, params=params).json()
        logger.info(f"获取到商品列表为：{resp}")
        if resp.get("error_code") == 40001:
            logger.error(MSG_MAP.get(resp.get("error_code")))

    def get_goods_info(self, goods_id):
        url = f"{self.base_url}/goods.html?goods_id={goods_id}"
        logger.debug(f"获取商品详情 {url}")
        resp = self.session.get(url).text
        raw_data = self._resolve_raw_data(resp)
        if raw_data is False:
            logger.error(f"商品【{goods_id}】没有信息 可能账号被封禁")
            return
        goods_info = raw_data["store"]["initDataObj"]["goods"]
        logger.info(f"商品详情 【{goods_id}】 【{goods_info.get('goodsName')}】 为：{goods_info}")


if __name__ == "__main__":
    ck = {

        # "api_uid": "Ck5oxWYcgAZgjQBYU9WdAg==",
        # "_nano_fp": "XpmaXqgYXqCxn5TJn9_e2MsNWzUS3ffo16ozNr7~",
        # "PDDAccessToken": "26DSZ3PG65OHAMXNLQIGRLXUKBMFE6SVSEVJQT5CX7ELVC6CCA4A121c274",
        # "pdd_user_id": "1576526274",
        # "pdd_user_uin": "YD7VU6OJE2DG3NSYML6ZPXB5DE_GEXDA",

        'api_uid': 'CiZuSGauOoAfEQBTE026Ag==',
        '_nano_fp': None,
        'PDDAccessToken': 'PUTY6PWDEWZD4MC2A2CR647BKMSHTV3P57C7CZLZ5FG33AX7KGIQ121c274',
        'pdd_user_id': '1576526274',
        'pdd_user_uin': 'YD7VU6OJE2DG3NSYML6ZPXB5DE_GEXDA',
        'pdd_vds': None

        # 'api_uid': 'CiHu0WauOy4+2QCGE3FzAg==', '_nano_fp': None, 'PDDAccessToken': 'XJLEILJVS3AGY5ISD3BWF4WI2DIV37L2F26RU74WODFNGFQ24IUA123d466', 'pdd_user_id': '7816067872724',
        # 'pdd_user_uin': 'GZMP25DYC5D4HUTUDRQAVMMOIQ_GEXDA', 'pdd_vds': None

    }
    test = PddCrawler(ck)
    # test.get_mall_info(mall_id="409099714")
    # test.get_mall_info(mall_id="102801257")
    # test.get_mall_goods_info(mall_id="102801257", page_no=1)
    # test.get_mall_goods_info(mall_id="102801257", page_no=2)
    # test.get_mall_goods_info(mall_id="102801257", page_no=3)
    # test.get_mall_goods_info(mall_id="1052959", page_no=1)
    # test.get_mall_goods_info(mall_id="1052959", page_no=2)
    # test.get_mall_info(mall_id="1052959")
    # test.get_mall_info(mall_id="109548654")
    test.get_mall_info(mall_id="109744208")
    # test.get_goods_info(goods_id='603056777621')
    # test.get_mall_goods_info(mall_id='409099714')
